package com.work.game.home.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.Request;
import com.anythink.nativead.api.ATNativeAdView;
import com.gyf.immersionbar.ImmersionBar;
import com.work.game.R;
import com.work.game.ad.MediationBannerAd;
import com.work.game.ad.MediationFeedAd;
import com.work.game.ad.MediationFullAd;
import com.work.game.ad.MediationRewardAd;
import com.work.game.ad.MediationRewardAdCallback;
import com.work.game.ad.MediationTablePlaqueAd;
import com.work.game.ad.inter.RewardAdCallbackInter;
import com.work.game.ad.inter.RewardAdFullAdInter;
import com.work.game.ad.inter.RewardAdInter;
import com.work.game.ad.kaku.TaKuInterstitialFullAd;
import com.work.game.ad.kaku.TaKuRewardAdCallback;
import com.work.game.ad.kaku.banner.TaKuBannerAdOBJ;
import com.work.game.ad.kaku.banner.TaKuBannerAdOne;
import com.work.game.ad.kaku.banner.TaKuBannerAdOneCW;
import com.work.game.ad.kaku.banner.TaKuBannerAdOneDT;
import com.work.game.ad.kaku.banner.TaKuBannerAdOneJL;
import com.work.game.ad.kaku.banner.TaKuBannerAdOneTop;
import com.work.game.ad.kaku.banner.TaKuBannerAdTwo;
import com.work.game.ad.kaku.interstitia.TaKuInterstitialAdOne;
import com.work.game.ad.kaku.interstitia.TaKuInterstitialAdOneCW;
import com.work.game.ad.kaku.interstitia.TaKuInterstitialAdOneDT;
import com.work.game.ad.kaku.interstitia.TaKuInterstitialAdOneJL;
import com.work.game.ad.kaku.nativie.TaKuNativeAdOneCW;
import com.work.game.ad.kaku.nativie.TaKuNativeAdOneDT;
import com.work.game.ad.kaku.nativie.TaKuNativeAdOneJL;
import com.work.game.ad.kaku.reward.TaKuRewardAdOne;
import com.work.game.config.UrlConfig;
import com.work.game.home.ui.activity.WithdrawalActivity;
import com.work.game.home.ui.enums.AdStatusEnum;
import com.work.game.home.ui.enums.RedisEnum;
import com.work.game.home.ui.enums.RiskEnum;
import com.work.game.home.ui.model.Answer;
import com.work.game.home.ui.model.TrandsName;
import com.work.game.home.ui.model.VersionUpdate;
import com.work.game.home.ui.model.vo.BaseVo;
import com.work.game.utils.StringSplit;
import com.work.game.utils.UpdateManager;
import com.work.game.utils.VersionUtils;
import com.work.game.utils.risk.DeviceUtils;
import com.work.game.volley.BaseFragment;
import com.work.game.volley.state.HUCState;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

public class ContentFragment extends BaseFragment implements RewardAdInter, RewardAdCallbackInter, RewardAdFullAdInter {
    private View view;


    //加载
    private AlertDialog alertDialog;

    //更新
    private UpdateManager updateManager;

    //答题卡
    private TextView tvLevel, tvValueAontent, tvValueA, tvValueB;
    List<TextView> textViewList;
    //答题 start

    //记录当前答题目数量
    private int indexTextViewList = 0;
    //记录答对题目数量
    private int answerCount = 0;
    private Answer answer;
    private List<Answer> answerList;
    private TextView tvMoneyRedPacket, tvMoneyGoldCoin, tvNickname, tvCode;
    //答题 send
    //获取用户激励视频广告
    private String orderId;


    private AlertDialog loadingDialogTransID;

    private TaKuRewardAdCallback taKuRewardAdCallback;
    private TaKuInterstitialFullAd taKuInterstitialFullAd;

    private TaKuBannerAdOneTop taKuBannerAdOneTop;
    private TaKuBannerAdOne taKuBannerAdOne;

    //初始化 插屏广告
    MediationTablePlaqueAd mediationTablePlaqueAd;

    //缓存用户奖励结果
    private Object userTrandsNameObject;

    private boolean isVisibleToUser = false;

    private TextView tvUsParentId, tvLoginTime;

    private CountDownTimer countDownTimer;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (ObjectUtil.isNotNull(view)) {
            return view;
        }
        view = inflater.inflate(R.layout.view_page_content_style, container, false);
        super.onCreateView(inflater, container, savedInstanceState);
        if (isVisibleToUser) {
            initAd();
        }
        //检测更新
        updateManager = new UpdateManager(this.getActivity());
        if (ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            //申请READ_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE}, HUCState.HUC_REQEUST_CODE_1);
        } else {
            //获取后台数据
            loadVersion();
        }
        tvCode.setText("ID:" + getSharedPreferences("id"));
        //加载题库
        String index = getSharedPreferences("currentSubject");
        if (StrUtil.isNotEmpty(index)) {
            indexTextViewList = Integer.parseInt(index);
        }
        String answerCountStr = getSharedPreferences("answerCount");
        if (StrUtil.isNotEmpty(answerCountStr)) {
            answerCount = Integer.parseInt(answerCountStr);
        }
        //加载题库
        loadQuestionBank();
        //初始化 全屏广告
        String fullAdId = getSharedPreferences(RedisEnum.AD_INSERT_FULL_SCREEN.getKey());
        taKuInterstitialFullAd = TaKuInterstitialFullAd.getInstance();
        taKuInterstitialFullAd.loadAd(this.getActivity(), fullAdId);
        taKuRewardAdCallback = TaKuRewardAdCallback.getInstance();
        ImmersionBar.with(this).titleBar(view.findViewById(R.id.layout_top)).init();
        return view;
    }


    @Override
    public void onStart() {
        super.onStart();
        tvNickname.setText(getSharedPreferences("nickname"));
        tvMoneyRedPacket.setText(getSharedPreferences("moneyRedPacket"));
        tvMoneyGoldCoin.setText(getSharedPreferences("moneyGoldCoin"));
        String usParentId = getSharedPreferences("usParentId");
        tvUsParentId.setText("渠道ID：" + usParentId);
        String loginTime = getSharedPreferences("loginTime");
        tvLoginTime.setText(loginTime);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisibleToUser = isVisibleToUser;
        if (ObjectUtil.isNotNull(countDownTimer)) {
            countDownTimer.cancel();
        }
        if (isVisibleToUser) {
            initAd();
        }
        super.setUserVisibleHint(isVisibleToUser);
    }


    @Override
    public void initView() {
        super.initView();
        //sf
        tvMoneyGoldCoin = view.findViewById(R.id.tv_moneyGoldCoin);
        tvMoneyRedPacket = view.findViewById(R.id.tv_moneyRedPacket);
        tvNickname = view.findViewById(R.id.tv_nickname);
        tvCode = view.findViewById(R.id.tv_code);

        //答题卡
        tvLevel = view.findViewById(R.id.tv_Level);
        tvValueAontent = view.findViewById(R.id.tv_value_content);
        tvValueA = view.findViewById(R.id.tv_value_c);
        tvValueB = view.findViewById(R.id.tv_value_d);

        tvUsParentId = view.findViewById(R.id.us_parent_id);
        tvLoginTime = view.findViewById(R.id.tv_login_time);

        answerList = new ArrayList<>();
        textViewList = new ArrayList<>(4);
        textViewList.add(tvValueA);
        textViewList.add(tvValueB);

    }

    @Override
    public void initClick() {
        super.initClick();
        // view.findViewById(R.id.tv_withdrawal).setOnClickListener(this);
        // view.findViewById(R.id.tv_withdrawal_hong_bao).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_withdrawal:
                sendIntent(this.getActivity(), WithdrawalActivity.class, String.valueOf(HUCState.HUC_REQEUST_CODE_1));
                break;
            case R.id.tv_withdrawal_hong_bao:
                sendIntent(this.getActivity(), WithdrawalActivity.class, String.valueOf(HUCState.HUC_REQEUST_CODE_2));
                break;
            case R.id.tv_value_a:
                setTextView(R.id.tv_value_a);
                break;
            case R.id.tv_value_b:
                setTextView(R.id.tv_value_b);
                break;
            case R.id.tv_value_c:
                setTextView(R.id.tv_value_c);
                break;
            case R.id.tv_value_d:
                setTextView(R.id.tv_value_d);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == HUCState.HUC_REQEUST_CODE_1 && resultCode == Activity.RESULT_OK) {
            loadVersion();
        }
    }

    @Override
    public void rewardAdSign(String ecpm) {
        alertDialog.dismiss();
        alertDialog = null;
        initAd();
    }

    @Override
    public void rewardAdCallback(String orderId) {
        this.orderId = orderId;
        if (AdStatusEnum.AD_STATUS_YES.getValue().equals(getSharedPreferences(RedisEnum.APP_FULL_SCREEN.getKey()))) {
            AlertDialog alertDialog = showDialogLoading();
            String key = getSharedPreferences(RedisEnum.TA_KU.getKey());
            if (RedisEnum.TA_KU.getValue().equals(key)) {
                taKuInterstitialFullAd.setRewardAdFullAdInter(this);
                taKuInterstitialFullAd.setToken(getSharedPreferences("deviceId"));
                taKuInterstitialFullAd.showAd(this.getActivity(), alertDialog);
            }
            //提前加载用户奖励
            BaseVo baseVo = new BaseVo();
            baseVo.setTransId(orderId);
            baseVo.setToken(getSharedPreferences("deviceId"));
            baseVo.setOaid(DeviceUtils.getInstance().getOaId(this.getActivity()));
            hucRequestInterfase.executeStr(this, TrandsName.class, HUCState.HUC_REQEUST_CODE_4, Request.Method.POST, UrlConfig.URL_TRANS_IDD, hucParameInterfase.getRequestParameter(baseVo), true);
        } else {
            isTransId();
        }
    }

    //副广加载失败处理
    @Override
    public void onError() {
        isTransId();

    }

    //副广关闭/跳过处理
    @Override
    public void onAdClose() {
        isTransId();
    }

    //检测是否有新更新
    private void loadVersion() {
        BaseVo baseVo = new BaseVo();
        baseVo.setToken(getSharedPreferences("deviceId"));
        hucRequestInterfase.executeStr(this, VersionUpdate.class, HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.URL_VERSION, hucParameInterfase.getRequestParameter(baseVo), true);
    }

    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                if (response instanceof VersionUpdate) {
                    VersionUpdate versionUpdate = (VersionUpdate) response;
                    if (VersionUtils.getAppVersionCode(this.getContext()) >= Integer.valueOf(versionUpdate.getVuVersionCode())) {
                        break;
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        if (!Environment.isExternalStorageManager()) {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                            startActivity(intent);
                        }
                    }
                    //更新
                    loadVersion(versionUpdate.getVuVersionName(), versionUpdate.getVuContent(), versionUpdate.getVuUrl());
                }
                loadDismiss();
                break;
            case HUCState.HUC_REQEUST_CODE_2:
                if (response instanceof List) {
                    answerList = (List<Answer>) response;
                    //加载题库
                    setRefreshAnswer(indexTextViewList);
                }
                loadDismiss();
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                if (response instanceof TrandsName) {
                    TrandsName trandsName = (TrandsName) response;
                    setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS.getKey(), trandsName.getRiskAdvertisingCoins());
                    setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS_THAN_EQUAL.getKey(), trandsName.getRiskAdvertisingCoinsThanEqual());
                    setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS_THAN_EQUAL_TWO.getKey(), trandsName.getRiskAdvertisingCoinsThanEqualTwo());
                    setSharedPreferences(RedisEnum.RISK_WHITE_LIST.getKey(), trandsName.getRiskWhiteList());
                    showAdvertisementReward(trandsName);
                }
                if (ObjectUtil.isNotNull(loadingDialogTransID)) {
                    loadingDialogTransID.dismiss();
                }
                loadingDialogTransID = null;
                if (userTrandsNameObject instanceof List || response instanceof List) {
                    Toast.makeText(this.getActivity(), "领取奖励失败", Toast.LENGTH_LONG).show();
                    initAd();
                    return;
                }
                break;
            case HUCState.HUC_REQEUST_CODE_4:
                userTrandsNameObject = response;
                break;
            default:
                break;
        }

    }

    @Override
    public void onFailStrType(int inputType, Object response) {
        super.onFailStrType(inputType, response);
    }

    //检测更新 start
    private void loadVersion(String usersionC, String content, String url) {
        //
        AlertDialog.Builder dialog = new AlertDialog.Builder(this.getActivity());
        View root = LayoutInflater.from(this.getActivity()).inflate(R.layout.item_version, null);
        ProgressBar progressBar = root.findViewById(R.id.pb_o);
        TextView versionRoot = root.findViewById(R.id.tv_version);
        TextView tvContent = root.findViewById(R.id.tv_content);
        tvContent.setText(content);
        versionRoot.setText("V" + usersionC);

        int roundRadius = 15; // 8dp 圆角半径 The x-radius of the oval used to round the corners

        //准备progressBar带圆角的背景Drawable
        GradientDrawable progressBg = new GradientDrawable();
        //设置圆角弧度
        progressBg.setCornerRadius(roundRadius);
        //设置绘制颜色
        progressBg.setColor(getResources().getColor(R.color.white_hui));

        //准备progressBar带圆角的进度条Drawable
        GradientDrawable progressContent = new GradientDrawable();
        progressContent.setCornerRadius(roundRadius);
        //设置绘制颜色，此处可以自己获取不同的颜色
        progressContent.setColor(getResources().getColor(R.color.home));

        //ClipDrawable是对一个Drawable进行剪切操作，可以控制这个drawable的剪切区域，以及相相对于容器的对齐方式
        ClipDrawable progressClip = new ClipDrawable(progressContent, Gravity.LEFT, ClipDrawable.HORIZONTAL);
        //Setup LayerDrawable and assign to progressBar
        //待设置的Drawable数组
        Drawable[] progressDrawables = {progressBg, progressClip};
        LayerDrawable progressLayerDrawable = new LayerDrawable(progressDrawables);
        //根据ID设置progressBar对应内容的Drawable
        progressLayerDrawable.setId(0, android.R.id.background);
        progressLayerDrawable.setId(1, android.R.id.progress);
        //设置progressBarDrawable
        progressBar.setProgressDrawable(progressLayerDrawable);
        root.findViewById(R.id.tv_cancel).setVisibility(View.GONE);
        dialog.setView(root);
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                root.findViewById(R.id.tv_ok).setEnabled(false);
                updateManager.showDownloadDialog(progressBar, alertDialog, url);
            }
        });
        root.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                alertDialog = null;
            }
        });
        alertDialog = dialog.create();
        alertDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog.setCancelable(false);
        alertDialog.show();
    }
    //检测更新 end

    //答题领取奖励页面 yes
    private void dialogAnswerYes(TextView textView) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this.getActivity());
        View root = LayoutInflater.from(this.getActivity()).inflate(R.layout.pop_advertisemen_yes_style, null);
        dialog.setView(root);
        alertAd(root, 1);
//        TextView tvTime = root.findViewById(R.id.tv_time);
//        View llVisible = root.findViewById(R.id.ll_visible);
        View llGone = root.findViewById(R.id.ll_gone);
        TextView tvUserId = root.findViewById(R.id.tv_user_id);
        TextView tvOk=root.findViewById(R.id.tv_ok);
        TextView tvLoginTime = root.findViewById(R.id.tv_login_time);
        String loginTime = getSharedPreferences("loginTime");
        tvLoginTime.setText(loginTime);
        tvUserId.setText("用户ID:" + getSharedPreferences("id"));
        TextView tvChannelId = root.findViewById(R.id.tv_channel_id);
        String usParentId = getSharedPreferences("usParentId");
        tvChannelId.setText("渠道ID：" + usParentId);
        TextView tvNumber = root.findViewById(R.id.tv_number);
        String dayNumber = getSharedPreferences(RedisEnum.DAILY_TASK_FREQUENCY.getKey());
        String dayRewardCount = getSharedPreferences("day_reward_count");
        int answerNum=indexTextViewList+1;
        tvNumber.setText("("+answerNum+"/"+dayNumber+")");
        String time = getSharedPreferences(RedisEnum.TIME_INTERVAL_ANSWER.getKey());
        ProgressBar progressBar=root.findViewById(R.id.progress_bar);
        try {
            double rewardCountTask= Double.valueOf(answerNum);
            double dayNumberAll= Double.valueOf(dayNumber);
            if(answerNum>0){
                int progressValue= (int) (rewardCountTask/dayNumberAll*100);
                progressBar.setProgress(progressValue);
            }else{
                progressBar.setProgress(0);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        CountDownTimer countDownTimer = new CountDownTimer(Integer.parseInt(time), 1000) { // 设置倒计时的总时间和间隔
            @Override
            public void onTick(long millisUntilFinished) {
//                tvTime.setEnabled(false);
                tvOk.setEnabled(false);
                tvOk.setText("立即领取("+millisUntilFinished / 1000 + "s)");
            }

            @Override
            public void onFinish() {
                llGone.setVisibility(View.VISIBLE);
                tvOk.setEnabled(true);
                tvOk.setText("立即领取");
            }
        };
        if (ObjectUtil.isNotNull(countDownTimer)) {
            countDownTimer.start(); // 启动倒计时
        }

        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AdStatusEnum.AD_STATUS_YES.getValue().equals(getSharedPreferences(RedisEnum.APP_ANSWER_INCENTIVE.getKey()))) {
                    //用户白名单
                    String risk_white_list = getSharedPreferences(RedisEnum.RISK_WHITE_LIST.getKey());
                    if (RiskEnum.RISK_YES.getValue().equals(risk_white_list)) {
                        AlertDialog alertDialogName = showDialogLoading();
                        String key = getSharedPreferences(RedisEnum.TA_KU.getKey());
                        if (RedisEnum.TA_KU.getValue().equals(key)) {
                            taKuRewardAdCallback.setUserId(getSharedPreferences("id"));
                            taKuRewardAdCallback.setToken(getSharedPreferences("deviceId"));
                            taKuRewardAdCallback.setBaseFragment(ContentFragment.this);
                            taKuRewardAdCallback.setRewardAdCallbackInter(ContentFragment.this);
                            taKuRewardAdCallback.setAlertDialog(alertDialogName);
                            taKuRewardAdCallback.showAd(ContentFragment.this.getActivity());
                        }
                        nextQuestion(textView);
                        alertDialog.dismiss();
                        alertDialog = null;
                        return;
                    }
                    Integer dayNumber = Integer.valueOf(getSharedPreferences(RedisEnum.DAILY_TASK_FREQUENCY.getKey(),"0"));
                    //每日激励视频可看N次
                    Integer dayCount = Integer.valueOf(getSharedPreferences("day_reward_count","0"));
                    if (dayCount >= dayNumber) {
                        Toast.makeText(ContentFragment.this.getActivity(), "今日任务已完成", Toast.LENGTH_LONG).show();
                        nextQuestion(textView);
                        alertDialog.dismiss();
                        alertDialog = null;
                        return;
                    }
                    //今日广告总金币允许N金币
                    String risk_advertising_coins = getSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS.getKey());
                    if (RiskEnum.RISK_YES.getValue().equals(risk_advertising_coins)) {
                        Toast.makeText(ContentFragment.this.getActivity(), "今日奖励已上限", Toast.LENGTH_LONG).show();
                        nextQuestion(textView);
                        alertDialog.dismiss();
                        alertDialog = null;
                        return;
                    }
                    //今日广告总金币N次平均值小于等于N金币
                    String risk_advertising_coins_than_equal = getSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS_THAN_EQUAL.getKey());
                    if (RiskEnum.RISK_YES.getValue().equals(risk_advertising_coins_than_equal)) {
                        Toast.makeText(ContentFragment.this.getActivity(), "贡献值过低", Toast.LENGTH_LONG).show();
                        nextQuestion(textView);
                        alertDialog.dismiss();
                        alertDialog = null;
                        return;
                    }
                    //今日广告总金币N次大于N金币小于等于N金币
                    String risk_advertising_coins_than_equal_two = getSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS_THAN_EQUAL_TWO.getKey());
                    if (RiskEnum.RISK_YES.getValue().equals(risk_advertising_coins_than_equal_two)) {
                        Toast.makeText(ContentFragment.this.getActivity(), "贡献值过低", Toast.LENGTH_LONG).show();
                        nextQuestion(textView);
                        alertDialog.dismiss();
                        alertDialog = null;
                        return;
                    }
                    String key = getSharedPreferences(RedisEnum.TA_KU.getKey());
                    if (RedisEnum.TA_KU.getValue().equals(key)) {
                        AlertDialog alertDialog = showDialogLoading();
                        taKuRewardAdCallback.setUserId(getSharedPreferences("id"));
                        taKuRewardAdCallback.setToken(getSharedPreferences("deviceId"));
                        taKuRewardAdCallback.setBaseFragment(ContentFragment.this);
                        taKuRewardAdCallback.setRewardAdCallbackInter(ContentFragment.this);
                        taKuRewardAdCallback.setAlertDialog(alertDialog);
                        taKuRewardAdCallback.showAd(ContentFragment.this.getActivity());
                    }
                }
                nextQuestion(textView);
                alertDialog.dismiss();
                alertDialog = null;
            }
        });
        root.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextQuestion(textView);
                alertDialog.dismiss();
                alertDialog = null;
                initAd();
            }
        });
        if (ObjectUtil.isNotNull(alertDialog)) {
            return;
        }
        alertDialog = dialog.create();
        alertDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog.getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = alertDialog.getWindow().getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        alertDialog.getWindow().setAttributes(layoutParams);
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    //错误页面 no
    private void dialogAnswerNo(TextView textView) {
        //判断提现账号
        AlertDialog.Builder dialog = new AlertDialog.Builder(this.getActivity());
        View root = LayoutInflater.from(this.getActivity()).inflate(R.layout.pop_advertisemen_no, null);
        dialog.setView(root);
        TextView tvQuestion = root.findViewById(R.id.tv_question);
        tvQuestion.setText(tvValueAontent.getText().toString());
        alertAd(root, 3);
        TextView tvTime = root.findViewById(R.id.tv_time);
        View llVisible = root.findViewById(R.id.ll_visible);
        View llGone = root.findViewById(R.id.ll_gone);
        String time = getSharedPreferences(RedisEnum.TIME_INTERVAL_ANSWER_ERROR.getKey());
        CountDownTimer countDownTimer = new CountDownTimer(Integer.parseInt(time), 1000) { // 设置倒计时的总时间和间隔
            @Override
            public void onTick(long millisUntilFinished) {
                tvTime.setEnabled(false);
                tvTime.setText(millisUntilFinished / 1000 + "s 重来");
            }

            @Override
            public void onFinish() {
                llGone.setVisibility(View.VISIBLE);
                llVisible.setVisibility(View.GONE);
            }
        };
        if (ObjectUtil.isNotNull(countDownTimer)) {
            countDownTimer.start(); // 启动倒计时
        }
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String taKu = getSharedPreferences(RedisEnum.TA_KU.getKey());
                AlertDialog loadingDoaLog = showDialogLoading();
                if (RedisEnum.TA_KU.getValue().equals(taKu)) {
                    TaKuRewardAdOne taKuRewardAdOne = TaKuRewardAdOne.getInstance();
                    taKuRewardAdOne.setToastContent("看完视频才能再来一次");
                    taKuRewardAdOne.setAlertDialog(loadingDoaLog);
                    taKuRewardAdOne.setContext(ContentFragment.this.getActivity());
                    taKuRewardAdOne.setRewardAdInter(ContentFragment.this);
                    taKuRewardAdOne.setToken(getSharedPreferences("deviceId"));
                    taKuRewardAdOne.showAd(ContentFragment.this.getActivity());
                }
            }
        });
        root.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextQuestion(textView);
                alertDialog.dismiss();
                alertDialog = null;
                initAd();


            }
        });
        if (ObjectUtil.isNotNull(alertDialog)) {
            return;
        }
        alertDialog = dialog.create();
        alertDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog.getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = alertDialog.getWindow().getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        alertDialog.getWindow().setAttributes(layoutParams);
        alertDialog.setCancelable(false);
        alertDialog.show();
    }


    //奖励页面 start
    @SuppressLint("MissingInflatedId")
    private void showAdvertisementReward(TrandsName trandsName) {
        //判断提现账号
        AlertDialog.Builder dialog = new AlertDialog.Builder(this.getActivity());
        View root = LayoutInflater.from(this.getActivity()).inflate(R.layout.pop_advertisement_reward, null);
        dialog.setView(root);
        TextView tvHongBao = root.findViewById(R.id.tv_hongbao);
        tvHongBao.setText("+" + trandsName.getValueHongBao());
        TextView tvYuanBao = root.findViewById(R.id.tv_yuanbao);
        tvYuanBao.setText("+" + trandsName.getValueJingBi());
        alertAd(root, 2);
        TextView tvTime = root.findViewById(R.id.tv_time);
        View llVisible = root.findViewById(R.id.ll_visible);
        View llGone = root.findViewById(R.id.ll_gone);
        String time = getSharedPreferences(RedisEnum.TIME_INTERVAL_ANSWER_RECEIVE.getKey());
        CountDownTimer countDownTimer = new CountDownTimer(Integer.parseInt(time), 1000) { // 设置倒计时的总时间和间隔
            @Override
            public void onTick(long millisUntilFinished) {
                tvTime.setEnabled(false);
                tvTime.setText(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                llGone.setVisibility(View.VISIBLE);
                llVisible.setVisibility(View.GONE);
            }
        };
        if (ObjectUtil.isNotNull(countDownTimer)) {
            countDownTimer.start(); // 启动倒计时
        }
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initAd();
                //修改页面的值
                int sum = Integer.parseInt(tvMoneyRedPacket.getText().toString()) + Integer.parseInt(trandsName.getValueHongBao());
                int sumGoldCoin = Integer.parseInt(tvMoneyGoldCoin.getText().toString()) + Integer.parseInt(trandsName.getValueJingBi());
                tvMoneyRedPacket.setText(String.valueOf(sum));
                tvMoneyGoldCoin.setText(String.valueOf(sumGoldCoin));
                //修改缓存
                setSharedPreferences("moneyRedPacket", String.valueOf(sum));
                setSharedPreferences("moneyGoldCoin", String.valueOf(sumGoldCoin));
                alertDialog.dismiss();
                alertDialog = null;
                if (ObjectUtil.isNotNull(userTrandsNameObject)) {
                    userTrandsNameObject = null;
                }
            }
        });
        if (ObjectUtil.isNotNull(alertDialog)) {
            return;
        }
        alertDialog = dialog.create();
        alertDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog.getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = alertDialog.getWindow().getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        alertDialog.getWindow().setAttributes(layoutParams);
        alertDialog.setCancelable(false);
        alertDialog.show();
    }
    //奖励页面 end

    //加载题库
    private void loadQuestionBank() {
        BaseVo baseVo = new BaseVo();
        baseVo.setToken(getSharedPreferences("deviceId"));
        hucRequestInterfase.executeStr(this, Answer.class, HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.URL_QUESTION_BANK, hucParameInterfase.getRequestParameter(baseVo), false);
    }

    //获取答题奖励
    private void isTransId() {
        if (userTrandsNameObject instanceof TrandsName) {
            TrandsName userTrandsName = (TrandsName) userTrandsNameObject;
            showAdvertisementReward(userTrandsName);
            return;
        }
        BaseVo baseVo = new BaseVo();
        baseVo.setTransId(orderId);
        baseVo.setToken(getSharedPreferences("deviceId"));
        baseVo.setOaid(DeviceUtils.getInstance().getOaId(this.getActivity()));
        loadingDialogTransID = showDialogLoading();
        hucRequestInterfase.executeStr(this, TrandsName.class, HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.URL_TRANS_IDD, hucParameInterfase.getRequestParameter(baseVo), true);
    }


    //填充答题选项卡样式
    private void setTextView(int p) {
        for (TextView textView : textViewList) {
            if (p == textView.getId()) {
                textView.setBackgroundResource(R.drawable.radius_home);
                textView.setTextColor(getResources().getColor(R.color.white_hui));
                isResult(textView);
            } else {
                textView.setBackgroundResource(R.drawable.radius_blue_1);
                textView.setTextColor(getResources().getColor(R.color.orange));
            }
        }
    }

    //答题结果验证
    public void isResult(TextView textView) {
        if (!answer.getQbResult().equals(textView.getText())) {
            dialogAnswerNo(textView);
            return;
        }
        answerCount = answerCount + 1;
        setSharedPreferences("answerCount", String.valueOf(answerCount));
        dialogAnswerYes(textView);
    }

    /**
     * 更新答题UI
     *
     * @param indexTextViewList
     */
    private void setRefreshAnswer(int indexTextViewList) {
        answer = answerList.get(indexTextViewList);
        tvLevel.setText(answer.getQbLevel());
        tvValueAontent.setText((indexTextViewList+1)+"."+answer.getQbContent());
        tvValueA.setText(answer.getQbValueA());
        tvValueB.setText(answer.getQbValueB());
    }

    //下一题
    private void nextQuestion(TextView textView) {
        indexTextViewList = ++indexTextViewList;
        if (indexTextViewList >= answerList.size()) {
            indexTextViewList = 0;
            setSharedPreferences("currentSubject", String.valueOf(indexTextViewList));
        }
        setRefreshAnswer(indexTextViewList);
        textView.setBackgroundResource(R.drawable.radius_blue_1);
        textView.setTextColor(getResources().getColor(R.color.orange));
        setSharedPreferences("currentSubject", String.valueOf(indexTextViewList));
    }

    private void initAd() {
        if (ObjectUtil.isNull(view)) {
            return;
        }
        String timeInterval = getSharedPreferences(RedisEnum.TIME_INTERVAL.getKey());
        countDownTimer = new CountDownTimer(Integer.parseInt(timeInterval), 1000) { // 设置倒计时的总时间和间隔
            @Override
            public void onTick(long millisUntilFinished) {
                tvValueA.setOnClickListener(null);
                tvValueB.setOnClickListener(null);
                tvLevel.setText(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                tvValueA.setOnClickListener(ContentFragment.this);
                tvValueB.setOnClickListener(ContentFragment.this);
                tvLevel.setText(answer.getQbLevel());
            }
        };
        if (ObjectUtil.isNotNull(countDownTimer)) {
            countDownTimer.start(); // 启动倒计时
        }

        ATNativeAdView flContentTop = view.findViewById(R.id.fl_content_top);
        ATNativeAdView flContentBottom = view.findViewById(R.id.fl_content_bottom);
        String key = getSharedPreferences(RedisEnum.TA_KU.getKey());
        if (RedisEnum.TA_KU.getValue().equals(key)) {
            TaKuBannerAdOBJ taKuBannerAd1 = new TaKuBannerAdOBJ();
            taKuBannerAd1.setToken(getSharedPreferences("deviceId"));
            taKuBannerAd1.load(getContext(), StringSplit.splitOrNull(getSharedPreferences(RedisEnum.BANNER.getKey()), StrUtil.COMMA, 2), flContentTop);

            TaKuBannerAdOBJ taKuBannerAd2 = new TaKuBannerAdOBJ();
            taKuBannerAd2.setToken(getSharedPreferences("deviceId"));
            taKuBannerAd2.load(getContext(),StringSplit.splitOrNull(getSharedPreferences(RedisEnum.BANNER.getKey()), StrUtil.COMMA, 3), flContentBottom);

            //全平广告
            TaKuInterstitialAdOne taKuInterstitialAdOne = TaKuInterstitialAdOne.getInstance();
            taKuInterstitialAdOne.setToken(getSharedPreferences("deviceId"));
            taKuInterstitialAdOne.showAd(this.getActivity());
        }
    }

    private void alertAd(View view, int index) {
        if (ObjectUtil.isNull(view)) {
            return;
        }
        ATNativeAdView flContent = view.findViewById(R.id.fl_content);
        ATNativeAdView flContentTop = view.findViewById(R.id.fl_content_top);

        String key = getSharedPreferences(RedisEnum.TA_KU.getKey());
        if (RedisEnum.TA_KU.getValue().equals(key)) {
            if (ObjectUtil.isNotNull(taKuBannerAdOneTop)) {
                taKuBannerAdOneTop.onBannerClose(null);
            }
            if (ObjectUtil.isNotNull(taKuBannerAdOne)) {
                taKuBannerAdOne.onBannerClose(null);
            }

            switch (index) {
                case 1:
                    TaKuNativeAdOneDT taKuNativeAdOneDT = TaKuNativeAdOneDT.getInstance();
                    taKuNativeAdOneDT.setmATNativeAdView(flContent);
                    taKuNativeAdOneDT.setToken(getSharedPreferences("deviceId"));
                    taKuNativeAdOneDT.showAd();

                    TaKuInterstitialAdOneDT taKuInterstitialAdOneDT = TaKuInterstitialAdOneDT.getInstance();
                    taKuInterstitialAdOneDT.setToken(getSharedPreferences("deviceId"));
                    taKuInterstitialAdOneDT.showAd(this.getActivity());

                    TaKuBannerAdOneDT taKuBannerAdOneDT = TaKuBannerAdOneDT.getInstance();
                    taKuBannerAdOneDT.setToken(getSharedPreferences("deviceId"));
                    taKuBannerAdOneDT.load(this.getActivity(), getSharedPreferences(RedisEnum.BANNER.getKey()).split(",")[7], flContentTop);

                    break;
                case 2:
                    TaKuNativeAdOneJL taKuNativeAdOneJT = TaKuNativeAdOneJL.getInstance();
                    taKuNativeAdOneJT.setmATNativeAdView(flContent);
                    taKuNativeAdOneJT.setToken(getSharedPreferences("deviceId"));
                    taKuNativeAdOneJT.showAd();
                    TaKuInterstitialAdOneJL taKuInterstitialAdOneJL = TaKuInterstitialAdOneJL.getInstance();
                    taKuInterstitialAdOneJL.setToken(getSharedPreferences("deviceId"));
                    taKuInterstitialAdOneJL.showAd(this.getActivity());

                    TaKuBannerAdOneJL taKuBannerAdOneJL = TaKuBannerAdOneJL.getInstance();
                    taKuBannerAdOneJL.setToken(getSharedPreferences("deviceId"));
                    taKuBannerAdOneJL.load(this.getActivity(), getSharedPreferences(RedisEnum.BANNER.getKey()).split(",")[8], flContentTop);
                    break;
                case 3:
                    //信息流
                    TaKuNativeAdOneCW taKuNativeAdOneCW = TaKuNativeAdOneCW.getInstance();
                    taKuNativeAdOneCW.setmATNativeAdView(flContent);
                    taKuNativeAdOneCW.setToken(getSharedPreferences("deviceId"));
                    taKuNativeAdOneCW.showAd();

                    TaKuInterstitialAdOneCW taKuInterstitialAdOneCW = TaKuInterstitialAdOneCW.getInstance();
                    taKuInterstitialAdOneCW.setToken(getSharedPreferences("deviceId"));
                    taKuInterstitialAdOneCW.showAd(this.getActivity());

                    TaKuBannerAdOneCW taKuBannerAdOneCW = TaKuBannerAdOneCW.getInstance();
                    taKuBannerAdOneCW.setToken(getSharedPreferences("deviceId"));
                    taKuBannerAdOneCW.load(this.getActivity(), getSharedPreferences(RedisEnum.BANNER.getKey()).split(",")[9], flContentTop);
                    break;
            }

        } else {
            mediationTablePlaqueAd = MediationTablePlaqueAd.getInstance();
            mediationTablePlaqueAd.showCacheInterstitialFullAd(this.getActivity(), null);
        }
    }
}
